#!/usr/bin/env python
import os, sys, string, sliplib, re, codecs

#SLiP to XML conversion

strHelp = """
USAGE: slip2xml [-h] [<input SLiP file> [<optional output XML file>]]

Options:
	-h : print this help screen
"""

if sys.argv[1] in ["-h", "-H"]:
	print strHelp
	sys.exit(0)


booVerbose = 0
pathSLIP = sys.argv[1]

if len(sys.argv) <= 2:
	pathXML = ""
else:
	pathXML = sys.argv[2]

#SLIP file to string
try:
	fdSLIP = open(pathSLIP, "r")
except:
	print "could not open file"
	sys.exit(1)
	
sSLIP = fdSLIP.read()
fdSLIP.close()

try:
	sUniSLIP = unicode(sSLIP, "ascii")
	strEncoding = "ascii"
except:
	try:
		sUniSLIP = unicode(sSLIP, "utf-8")
		strEncoding = "utf-8"
	except:
		print "Error: encoding not supported"
		

#SLIP string to XML string
sXML = sliplib.slip2xml(sUniSLIP)

#see if XML has preferred encoding
lsXMLLines = string.split(sXML, u"\n")
for strLine in lsXMLLines:
	if string.strip(strLine) != "":
		strTopXML = strLine
		break
	else:
		continue
		
reXMLEncoding = re.compile(u"encoding=(?:'|\")(\\S+)(?:'|\")", re.U | re.I)
lsEncoding = reXMLEncoding.findall(strTopXML)

if len(lsEncoding) != 0:
	preferredXMLEnc = lsEncoding[0]
else:
	preferredXMLEnc = sys.getdefaultencoding()



sXML = string.replace(sXML, u"\n", os.linesep)
#Save XML file


if not pathXML == "":
	fdXML = codecs.open(pathXML, "w", preferredXMLEnc)
	fdXML.write(sXML)
	fdXML.close()
else:
	sys.stdout.write(sXML.encode(preferredXMLEnc))

sys.exit(0)